/**
 * Created by jinglupeng on 2/12/16.
 */

var api = window.api = require('/modules/monitor/api/kafka.js');

var $root = $('#group_offset');
var $groups = $root.find('[name=groups]');
var $reload = $root.find('[name=reload_button]');

var groupsPromise = api.loadGroups();
groupsPromise.then(function (groups) {
    var html = '';
    for (var i = 0; i < groups.length; i++) {
        html = html + '<option value="' + groups[i] + '">' + groups[i] + '</option>';
    }
    $groups.empty().append(html);
});

$groups.on('change', function () {
    var group = $(this).val();
    renderGroupOffsets(group);
});

$reload.on('click', function () {
    var group = $groups.val();
    renderGroupOffsets(group);
});

function renderGroupOffsets(group) {
    var offsetsPromise = api.loadGroupOffset(group);
    offsetsPromise.then(function (resp) {
        var offsets = resp.offsets || [];
        var result = {};
        for (var i = 0; i < offsets.length; i++) {
            var offset = offsets[i];
            var topic = offset.topic;
            var data = result[topic] || {
                    topic: topic,
                    logSize: 0,
                    offset: 0
                };
            data.logSize += offset.logSize;
            data.offset += offset.offset;
            result[topic] = data;
        }
        var html = '';
        for (var topic in result) {
            var data = result[topic];
            var last = data.logSize - data.offset;
            if (last > 0) {
                html = html + '<tr><td>' + data.topic + '</td><td>' + data.logSize + '</td><td>' + data.offset + '</td><td>' + last + '</td></tr>';
            }
        }
        $root.find('tbody').empty().append(html);
    });
}
